package cn.itsource.basic.service.impl;

import cn.itsource.basic.domain.BaseDomain;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.query.PageList;
import cn.itsource.basic.service.IBaseService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

public class BaseServiceImpl<T extends BaseDomain, Q extends BaseQuery> implements IBaseService<T, Q> {
    @Autowired
    private Mapper<T> mapper;

    @Override
    public PageList<T> getAllByPage(Q q) {
        //1.传递参数
         PageHelper.startPage(q.getPageNum(), q.getPageSize());

        //2.查询所有
        List<T> all = mapper.selectAll();

        //3.使用分页插件封装参数
        PageInfo<T> pageInfo = new PageInfo<>(all);

        //4.使用自己分页插件封装数据
        PageList<T> pageList = new PageList<>(pageInfo.getTotal(), pageInfo.getList());

        return pageList;
    }

    @Override
    public void saveOrUpdate(T t) {

        if (t.getId()==null){
            //没有id就新增
            mapper.insertSelective(t);
        }else{
            //有id就修改
            mapper.updateByPrimaryKeySelective(t);
        }

    }

    @Override
    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);

    }
}
